package com.avapir.snake.Actors;

import java.util.Vector;

import com.avapir.snake.Actors.PC.Snake;
import com.avapir.snake.UI.Game;

public class Updater {

	/**
	 * Extracts {@code snakes} from {@code Game} class here
	 */
	private static Vector<Snake> snakes;
public static long steps = 0;
	/**
	 * Current maximum earned score
	 */
	private static double maxScore;

	/**
	 * Battle logger link
	 */

	/**
	 * @return current high score in game
	 */
	public static double getMaxScore() {
		return maxScore;
	}

	/**
	 * Game updater<br>
	 * Method checks condition of the game, moves snakes and feed them if
	 * possible
	 */
	public static void update() {
		steps++;
		snakes = Game.getSnakes();

		checkForAppropriateSnakesCount();
		checkForGameEndByAliveLeftAmount();
		checkForGameEndByScoreThreshold();

		// long time;
		// time = System.currentTimeMillis();

		crawling();
		// ai[ololo] = "{"+(System.currentTimeMillis() - time) +
		// ", "+aliveSnakesCounter+"}";
		// time = System.currentTimeMillis();

		lunching();

		// lunch[ololo] = "{"+(System.currentTimeMillis() - time) +
		// ", "+aliveSnakesCounter+"}";
		// if(ololo==19) {
		// log.println(Arrays.toString(ai));
		// log.println(Arrays.toString(lunch));
		// }
		// ololo++;
	}

	/**
	 * RTFMethodName
	 */
	private static void checkForAppropriateSnakesCount() {
		if (snakes.size() > 10000)
			throw new RuntimeException("2much");
	}

	/**
	 * RTFMethodName
	 */
	private static void checkForGameEndByAliveLeftAmount() {
		if (Snake.aliveSnakesLeft == 1) {
			for (Snake s : snakes) {
				if (s.isAlive()) {
					Game.gameOver(s);
				}
			}
		}
	}

	/**
	 * RTFMethodName
	 */
	private static void checkForGameEndByScoreThreshold() {
		for (Snake s : snakes) {
			double score = s.getScore();
			if (score > maxScore) {
				maxScore = score;

				if (score >= Game.getWinScore()) {
					Game.gameOver(s);
				}
			}
		}
	}

	/**
	 * Process snakes movement
	 */
	private static void crawling() {
		for (Snake s : snakes) {
			if (s.isAlive())
				s.move();
		}
	}

	/**
	 * Process snakes eating food and each other
	 */
	private static void lunching() {
		for (Snake s : snakes) {
			if (s.isAlive())
				s.lunch();
		}
	}
}